package com.aw.guiguzi.widgets

import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Spinner
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aw.baselib.base.AwBaseConstant
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwDisplayUtil
import com.aw.baselib.util.AwLog
import com.aw.baselib.util.AwPopupwindowUtil
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.AwSoftKeyboardUtil
import com.aw.guiguzi.BuildConfig
import com.aw.guiguzi.R
import com.aw.guiguzi.adapter.NumSingleCheckAdapter
import com.aw.guiguzi.base.MyApp.Companion.mAllBettingNumsList
import com.aw.guiguzi.bean.NumItemBean
import com.aw.guiguzi.enums.NumBettingEnums
import com.aw.guiguzi.util.AppCacheUtil
import com.chad.library.adapter.base.BaseQuickAdapter
import java.util.Arrays

class Num3SingleCheckPopupWindow(
    private val mActivity: Activity,
    callback: OnResultCallback?,
    dismissListener: OnDismissListener?
) : PopupWindow() {
    private val contentView: View
    private val rg_block1: RadioGroup
    private val rg_block2: RadioGroup
    private val mAdapter: NumSingleCheckAdapter
    private var mList: MutableList<NumItemBean> = ArrayList()
    private var mPreCheckedBtn: RadioButton? = null

    init {
        mList = mAllBettingNumsList.toMutableList()
        contentView = View.inflate(mActivity, R.layout.view_popupwindow_num_3_single_check, null)
        val rcv_data = contentView.findViewById<RecyclerView>(R.id.rcv_data)
        val tv_config = contentView.findViewById<Spinner>(R.id.tv_config)
        val iv_close = contentView.findViewById<ImageView>(R.id.iv_close)
        val tv_submit = contentView.findViewById<TextView>(R.id.tv_submit)
        val tv_title = contentView.findViewById<TextView>(R.id.tv_title)
        rg_block1 = contentView.findViewById(R.id.rg_block1)
        rg_block2 = contentView.findViewById(R.id.rg_block2)
        tv_title.visibility = if (BuildConfig.DEBUG) View.GONE else View.VISIBLE
        mAdapter = NumSingleCheckAdapter()
        AwRecyclerViewUtil.setRecyclerViewGridlayout(
            mActivity,
            rcv_data,
            mAdapter,
            5,
            AwDisplayUtil.dip2px(mActivity, 2f)
        )
        mAdapter.addAllData(mList)
        setListener()
        tv_config.setSelection(defaultConfigCountIndex)
        tv_config.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                setListItemCount(parent.selectedItem as String)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        iv_close.setOnClickListener { v: View? -> dismiss() }
        tv_submit.setOnClickListener { v: View? ->
            if (null != callback) {
                val selectList: MutableList<NumItemBean?> = ArrayList()
                for (itemBean in mList) {
                    if (itemBean!!.isChecked) {
                        selectList.add(itemBean)
                    }
                }
                AwSoftKeyboardUtil.hideSoftKeyboard(mActivity)
                callback.onResult(selectList)
            }
            dismiss()
        }
        contentView.findViewById<View>(R.id.iv_delConfigNums)
            .setOnClickListener { v: View? -> clearAllSelect() }
        mAdapter.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val itemBean = adapter.getItem(position) as NumItemBean?
            itemBean!!.isChecked = !itemBean.isChecked
            mAdapter.notifyDataSetChanged()
        }
        setContentView(contentView)
        this.width = ViewGroup.LayoutParams.MATCH_PARENT
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        this.animationStyle = com.aw.baselib.R.style.sytle_anim_pop_in_out
        this.isFocusable = true
        this.isTouchable = true
        this.isOutsideTouchable = true
        setBackgroundDrawable(BitmapDrawable())
        this.update()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.overlapAnchor = true
        }
        if (dismissListener == null) {
            setOnDismissListener {
                val lp = mActivity.window.attributes
                lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_NORMAL
                mActivity.window.attributes = lp
            }
        } else {
            setOnDismissListener(dismissListener)
        }
    }

    private fun clearAllSelect() {
        for (itemBean in mList) {
            itemBean!!.isChecked = false
        }
        mAdapter.notifyDataSetChanged()
    }

    private val defaultConfigCountIndex: Int
        private get() {
            val list = Arrays.asList(*mActivity.resources.getStringArray(R.array.config_count))
            return list.indexOf(AppCacheUtil.getBettingConfigCount())
        }

    private fun setListItemCount(name: String) {
        if (AwDataUtil.isEmpty(mList)) {
            return
        }
        AppCacheUtil.setBettingConfigCount(name)
        for (itemBean in mList) {
            if (name == NumBettingEnums.MODE_1_1_10.name) {
                itemBean!!.setSilverCount(1)
                itemBean.setSkinCount(1)
                itemBean.setGemstoneCount(10)
            } else if (name == NumBettingEnums.MODE_1_1_20.name) {
                itemBean!!.setSilverCount(1)
                itemBean.setSkinCount(1)
                itemBean.setGemstoneCount(20)
            } else if (name == NumBettingEnums.MODE_1_1_40.name) {
                itemBean!!.setSilverCount(1)
                itemBean.setSkinCount(1)
                itemBean.setGemstoneCount(40)
            } else if (name == NumBettingEnums.MODE_2_2_20.name) {
                itemBean!!.setSilverCount(2)
                itemBean.setSkinCount(2)
                itemBean.setGemstoneCount(20)
            } else if (name == NumBettingEnums.MODE_2_2_40.name) {
                itemBean!!.setSilverCount(2)
                itemBean.setSkinCount(2)
                itemBean.setGemstoneCount(40)
            } else if (name == NumBettingEnums.MODE_3_3_30.name) {
                itemBean!!.setSilverCount(3)
                itemBean.setSkinCount(3)
                itemBean.setGemstoneCount(30)
            } else if (name == NumBettingEnums.MODE_4_4_40.name) {
                itemBean!!.setSilverCount(4)
                itemBean.setSkinCount(4)
                itemBean.setGemstoneCount(40)
            } else if (name == NumBettingEnums.MODE_5_5_50.name) {
                itemBean!!.setSilverCount(5)
                itemBean.setSkinCount(5)
                itemBean.setGemstoneCount(50)
            } else if (name == NumBettingEnums.MODE_5_5_100.name) {
                itemBean!!.setSilverCount(5)
                itemBean.setSkinCount(5)
                itemBean.setGemstoneCount(100)
            } else if (name == NumBettingEnums.MODE_10_10_100.name) {
                itemBean!!.setSilverCount(10)
                itemBean.setSkinCount(10)
                itemBean.setGemstoneCount(100)
            } else if (name == NumBettingEnums.MODE_10_10_200.name) {
                itemBean!!.setSilverCount(10)
                itemBean.setSkinCount(10)
                itemBean.setGemstoneCount(200)
            } else {
                val bettingCustomArrays = AppCacheUtil.getBettingCustom().split("/".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                itemBean!!.setSilverCount(AwDataUtil.getIntValue(bettingCustomArrays[0]))
                itemBean.setSkinCount(AwDataUtil.getIntValue(bettingCustomArrays[1]))
                itemBean.setGemstoneCount(AwDataUtil.getIntValue(bettingCustomArrays[2]))
            }
        }
    }

    private fun setSelect(selectArray: IntArray) {
        for (num in selectArray) { //0 6 7 8 9
            AwLog.d("setSelect num: $num")
            for (itemBean in mList) { // 0 1 2 3 4 5 6 7 8 9
                if (AwDataUtil.getIntValue(itemBean!!.name) == num) {
                    itemBean.isChecked = true
                }
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    private fun setListener() {
        rg_block1.setOnCheckedChangeListener { group: RadioGroup, checkedId: Int ->
            if (mPreCheckedBtn != null) {
                mPreCheckedBtn!!.isChecked = false
            }
            mPreCheckedBtn = group.findViewById(checkedId)
            clearAllSelect()
            when (checkedId) {
                R.id.rBtn012 -> setSelect(intArrayOf(0, 1, 2))
                R.id.rBtn123 -> setSelect(intArrayOf(1, 2, 3))
                R.id.rBtn234 -> setSelect(intArrayOf(2, 3, 4))
                R.id.rBtn345 -> setSelect(intArrayOf(3, 4, 5))
                R.id.rBtn456 -> setSelect(intArrayOf(4, 5, 6))
            }
        }
        rg_block2.setOnCheckedChangeListener { group: RadioGroup, checkedId: Int ->
            if (mPreCheckedBtn != null) {
                mPreCheckedBtn!!.isChecked = false
            }
            mPreCheckedBtn = group.findViewById(checkedId)
            clearAllSelect()
            when (checkedId) {
                R.id.rBtn567 -> setSelect(intArrayOf(5, 6, 7))
                R.id.rBtn678 -> setSelect(intArrayOf(6, 7, 8))
                R.id.rBtn789 -> setSelect(intArrayOf(7, 8, 9))
                R.id.rBtn890 -> setSelect(intArrayOf(8, 9, 0))
                R.id.rBtn901 -> setSelect(intArrayOf(9, 0, 1))
            }
        }
    }

    /**
     * 展示窗口
     */
    fun show(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        this.showAsDropDown(parent, 0, 0)
    }

    fun showAsLocation(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationNoAlpha(parent: View?) {
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationBottom(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        showAtLocation(parent, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
    }

    /**
     * calendar菜单选择监听接口
     */
    interface OnResultCallback {
        fun onResult(list: List<NumItemBean?>?)
    }
}